#include <stdio.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include <modbus/modbus.h>

/* The goal of this program is to check all major functions of
   libmodbus:
   - write_coil
   - read_bits
   - write_coils
   - write_register
   - read_registers
   - write_registers
   - read_registers
   All these functions are called with random values on a address
   range defined by the following defines.
*/
#define LOOP 1
#define SERVER_ID 17
#define ADDRESS_START 0
#define ADDRESS_END 99

/* At each loop, the program works in the range ADDRESS_START to
 * ADDRESS_END then ADDRESS_START + 1 to ADDRESS_END and so on.
 */
int main(void)
{
    modbus_t *ctx;
    int rc;
    int nb_fail;
    int nb_loop;
    int addr;
    int nb;
    uint8_t *tab_rq_bits;
    uint8_t *tab_rp_bits;
    uint16_t *tab_rq_registers;
    uint16_t *tab_rw_rq_registers;
    uint16_t *tab_rp_registers;

    /* TCP */
    //指定服务器地址与端口号
    ctx = modbus_new_tcp("127.0.0.1", 1502);
    // modbus_set_debug(ctx, TRUE);

    //与服务器建立连接
    if (modbus_connect(ctx) == -1)
    {
        fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

    /* Allocate and initialize the different memory spaces */
    //初始化读取地址空间的偏移量
    nb = ADDRESS_END - ADDRESS_START;

    tab_rq_bits = (uint8_t *)malloc(nb * sizeof(uint8_t));
    memset(tab_rq_bits, 0, nb * sizeof(uint8_t));

    tab_rp_bits = (uint8_t *)malloc(nb * sizeof(uint8_t));
    memset(tab_rp_bits, 0, nb * sizeof(uint8_t));

    tab_rq_registers = (uint16_t *)malloc(nb * sizeof(uint16_t));
    memset(tab_rq_registers, 0, nb * sizeof(uint16_t));

    tab_rp_registers = (uint16_t *)malloc(nb * sizeof(uint16_t));
    memset(tab_rp_registers, 0, nb * sizeof(uint16_t));

    tab_rw_rq_registers = (uint16_t *)malloc(nb * sizeof(uint16_t));
    memset(tab_rw_rq_registers, 0, nb * sizeof(uint16_t));

    nb_loop = nb_fail = 0;
    while (nb_loop++ < LOOP)
    {
        for (addr = ADDRESS_START; addr < ADDRESS_END; addr++)
        {
            int i;

            /* Random numbers (short) */
            for (i = 0; i < nb; i++)
            {
                tab_rq_registers[i] = (uint16_t)(65535.0 * rand() / (RAND_MAX + 1.0)); //地址 0 - 65535 的随机值 相对地址
                tab_rw_rq_registers[i] = ~tab_rq_registers[i];                         //对应位取反
                tab_rq_bits[i] = tab_rq_registers[i] % 2;                              //取余 0 或 1
            }
            nb = ADDRESS_END - addr; //偏移量

            /* WRITE BIT */
            //使用功能码0x05(写入单个线圈) 在地址addr上写值tab_rq_bits[0] 值为true or false
            rc = modbus_write_bit(ctx, addr, tab_rq_bits[0]);
            if (rc != 1)
            {
                printf("ERROR modbus_write_bit (%d)\n", rc);
                printf("Address = %d, value = %d\n", addr, tab_rq_bits[0]);
                nb_fail++;
            }
            else
            {
                // 使用功能码0x01(读取输出线圈)，读取 1 个位（线圈)的状态到读取到地址addr, 并存储到tab_rp_bits
                rc = modbus_read_bits(ctx, addr, 1, tab_rp_bits);
                if (rc != 1 || tab_rq_bits[0] != tab_rp_bits[0])
                {
                    printf("ERROR modbus_read_bits single (%d)\n", rc);
                    printf("address = %d\n", addr);
                    nb_fail++;
                }
            }

            /* MULTIPLE BITS */
            //使用功能码0x0F(写入多个线圈),从tab_rq_bits数组写nb个位（线圈）到地址addr
            rc = modbus_write_bits(ctx, addr, nb, tab_rq_bits);
            if (rc != nb)
            {
                printf("ERROR modbus_write_bits (%d)\n", rc);
                printf("Address = %d, nb = %d\n", addr, nb);
                nb_fail++;
            }
            else
            {
                // 使用功能码0x01(读取输出线圈)，读取 nb 个位（线圈)的状态到读取到地址addr, 并存储到tab_rp_bits
                rc = modbus_read_bits(ctx, addr, nb, tab_rp_bits);
                if (rc != nb)
                {
                    printf("ERROR modbus_read_bits\n");
                    printf("Address = %d, nb = %d\n", addr, nb);
                    nb_fail++;
                }
                else
                {
                    for (i = 0; i < nb; i++)
                    {
                        if (tab_rp_bits[i] != tab_rq_bits[i])
                        {
                            printf("ERROR modbus_read_bits\n");
                            printf("Address = %d, value %d (0x%X) != %d (0x%X)\n",
                                   addr,
                                   tab_rq_bits[i],
                                   tab_rq_bits[i],
                                   tab_rp_bits[i],
                                   tab_rp_bits[i]);
                            nb_fail++;
                        }
                    }
                }
            }

            /* SINGLE REGISTER */
            //使用功能码0x06(写入单个寄存器)，将数据tab_rq_registers[0]写入保持寄存器，开始地址是addr
            rc = modbus_write_register(ctx, addr, tab_rq_registers[0]);
            if (rc != 1)
            {
                printf("ERROR modbus_write_register (%d)\n", rc);
                printf("Address = %d, value = %d (0x%X)\n",
                       addr,
                       tab_rq_registers[0],
                       tab_rq_registers[0]);
                nb_fail++;
            }
            else
            {
                //使用功能码0x03，从远程地址addr开始读取共1位的状态到tab_rp_registers
                rc = modbus_read_registers(ctx, addr, 1, tab_rp_registers);
                if (rc != 1)
                {
                    printf("ERROR modbus_read_registers single (%d)\n", rc);
                    printf("Address = %d\n", addr);
                    nb_fail++;
                }
                else
                {
                    if (tab_rq_registers[0] != tab_rp_registers[0])
                    {
                        printf("ERROR modbus_read_registers single\n");
                        printf("Address = %d, value = %d (0x%X) != %d (0x%X)\n",
                               addr,
                               tab_rq_registers[0],
                               tab_rq_registers[0],
                               tab_rp_registers[0],
                               tab_rp_registers[0]);
                        nb_fail++;
                    }
                }
            }

            /* MULTIPLE REGISTERS */
            //
            rc = modbus_write_registers(ctx, addr, nb, tab_rq_registers);
            if (rc != nb)
            {
                printf("ERROR modbus_write_registers (%d)\n", rc);
                printf("Address = %d, nb = %d\n", addr, nb);
                nb_fail++;
            }
            else
            {
                rc = modbus_read_registers(ctx, addr, nb, tab_rp_registers);
                if (rc != nb)
                {
                    printf("ERROR modbus_read_registers (%d)\n", rc);
                    printf("Address = %d, nb = %d\n", addr, nb);
                    nb_fail++;
                }
                else
                {
                    for (i = 0; i < nb; i++)
                    {
                        if (tab_rq_registers[i] != tab_rp_registers[i])
                        {
                            printf("ERROR modbus_read_registers\n");
                            printf("Address = %d, value %d (0x%X) != %d (0x%X)\n",
                                   addr,
                                   tab_rq_registers[i],
                                   tab_rq_registers[i],
                                   tab_rp_registers[i],
                                   tab_rp_registers[i]);
                            nb_fail++;
                        }
                    }
                }
            }
            /* R/W MULTIPLE REGISTERS */
            rc = modbus_write_and_read_registers(
                ctx, addr, nb, tab_rw_rq_registers, addr, nb, tab_rp_registers);
            if (rc != nb)
            {
                printf("ERROR modbus_read_and_write_registers (%d)\n", rc);
                printf("Address = %d, nb = %d\n", addr, nb);
                nb_fail++;
            }
            else
            {
                for (i = 0; i < nb; i++)
                {
                    if (tab_rp_registers[i] != tab_rw_rq_registers[i])
                    {
                        printf("ERROR modbus_read_and_write_registers READ\n");
                        printf("Address = %d, value %d (0x%X) != %d (0x%X)\n",
                               addr,
                               tab_rp_registers[i],
                               tab_rw_rq_registers[i],
                               tab_rp_registers[i],
                               tab_rw_rq_registers[i]);
                        nb_fail++;
                    }
                }

                rc = modbus_read_registers(ctx, addr, nb, tab_rp_registers);
                if (rc != nb)
                {
                    printf("ERROR modbus_read_registers (%d)\n", rc);
                    printf("Address = %d, nb = %d\n", addr, nb);
                    nb_fail++;
                }
                else
                {
                    for (i = 0; i < nb; i++)
                    {
                        if (tab_rw_rq_registers[i] != tab_rp_registers[i])
                        {
                            printf("ERROR modbus_read_and_write_registers WRITE\n");
                            printf("Address = %d, value %d (0x%X) != %d (0x%X)\n",
                                   addr,
                                   tab_rw_rq_registers[i],
                                   tab_rw_rq_registers[i],
                                   tab_rp_registers[i],
                                   tab_rp_registers[i]);
                            nb_fail++;
                        }
                    }
                }
            }
        }

        printf("Test: ");
        if (nb_fail)
            printf("%d FAILS\n", nb_fail);
        else
            printf("SUCCESS\n");
    }

    /* Free the memory */
    free(tab_rq_bits);
    free(tab_rp_bits);
    free(tab_rq_registers);
    free(tab_rp_registers);
    free(tab_rw_rq_registers);

    /* Close the connection */
    modbus_close(ctx);
    modbus_free(ctx);

    return 0;
}